package com.vframework.cms.document.controller;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.util.StringUtil;
import com.util.UUIDUtil;
import com.vframework.base.controller.BaseController;
import com.vframework.base.exception.BaseException;
import com.vframework.cms.document.model.DocumentBean;
import com.vframework.cms.document.service.DocumentService;
import com.vframework.common.constant.BusinessConstant;
import com.vframework.common.constant.SessionConstant;
/***************************************************************
 * Name:        DocumentController.java     
 * Create At:   2017-08-08
 * Module:      素材库
 * Description: [素材库-包括查询、修改，添加功能]
 * Author       shanzhitong
 * ------------------------------------------------------------
 * 修改历史
 * 序号   日期                修改人              修改原因
 * 1
***************************************************************/
@Controller
@RequestMapping("DocumentController")
public class DocumentController extends BaseController {
    
    private static final String BASE_PATH = "com/vframework/cms/document/pages/";
    
    @Autowired
    private DocumentService documentService;
    
    @RequestMapping(value = "begin")
    private String begin(Model model) {
        //param_parentId: 当前list属于哪个文件夹
        super.paramMap.put("param_parentId", "0");
        request.setAttribute("param_parentId", "0");
        return getDocumentList(model);
     }

    @RequestMapping(value = "getDialogList")
    private String getDialogList(Model model) {
        request.setAttribute("choosemore", request.getParameter("choosemore"));
        request.setAttribute("param_type", request.getParameter("param_type"));
        return BASE_PATH + "documentDialogList";
    }
    
    @RequestMapping(value = "DialogPageList")
    @ResponseBody
    private Map<String, Object> DialogPageList(Model model) {
        Map<String, Object> resMap = new HashMap<String, Object>();
        super.paramMap.put("param_parentId", super.paramMap.get("param_parentId") == null ? "0" : super.paramMap.get("param_parentId"));
        try {
            List<DocumentBean> list = null;
            List<DocumentBean> parents = null;
            int pageCount = 0;
            pageCount = documentService.getCount(super.paramMap);
            if (pageCount > 0) {
                super.setPageInfo(pageCount);
                list = documentService.getList(super.paramMap);
            }
            if (super.paramMap.get("param_parentId") != null && !"0".equals(super.paramMap.get("param_parentId"))) {
                parents = documentService.getParents((String) super.paramMap.get("param_parentId"));
            }
            //页数
            int totalPage;
            int p = Integer.parseInt(String.valueOf(super.paramMap.get("param_ipagecount")));
            if (pageCount % p == 0) {
                totalPage = pageCount / p;
            }
            else {
                totalPage = pageCount / p + 1;
            }
            resMap.put("list", list);
            resMap.put("parents", parents);
            resMap.put("totalPage", totalPage);
        } catch (Exception e) {
            super.message("查询失败: " + e.getMessage());
            e.printStackTrace();
            return resMap;
        }
        return resMap;
    }
    
    /**
     * Author:shanzhitong
     * Create At:2017-08-08
     * Description: [文件管理--文件列表]
     * @return String
     */
    @RequestMapping(value = "getDocumentList")
    private String getDocumentList(Model model) {
        try {
            List<DocumentBean> list = new ArrayList<DocumentBean>();
            int pageCount = 0;
            pageCount = documentService.getCount(super.paramMap);
            if (pageCount > 0) {
                super.setPageInfo(pageCount);
                list = documentService.getList(super.paramMap);
            }
            model.addAttribute("list", list);
            if (super.paramMap.get("param_parentId") != null && !"0".equals(super.paramMap.get("param_parentId"))) {
                model.addAttribute("parent", documentService.getById((String) super.paramMap.get("param_parentId")));
            }
            request.setAttribute("param_parentId",super.paramMap.get("param_parentId"));
            request.setAttribute("pageCount",pageCount);
            request.setAttribute("actionurl","DocumentController/getDocumentList.do");
        } catch (Exception e) {
            super.message("查询失败: " + e.getMessage());
            return BASE_PATH + "documentList";
        }
        return BASE_PATH + "documentList";
    }

    @RequestMapping(value = "edit")
    private String edit(Model model) {
        String parentId = request.getParameter("parentId");
        String fileId = request.getParameter("fileId");
        if (StringUtil.isEmpty(parentId)) {
            parentId = "0";
        }
        DocumentBean parentBean = new DocumentBean();
        if (!"0".equals(parentId)) {
            try {
                parentBean = documentService.getById(parentId);
            } catch (BaseException e) {
                e.printStackTrace();
            }
        }
        model.addAttribute("parentBean", parentBean);
        DocumentBean documentBean = new DocumentBean();
        if (!StringUtil.isEmpty(fileId)) {
            try {
                documentBean = documentService.getById(fileId);
            } catch (BaseException e) {
                super.message("查询失败: " + e.getMessage());
                e.printStackTrace();
            }
        }
        model.addAttribute("documentBean", documentBean);
        return BASE_PATH + "documentAddFile";
    }
    
    @RequestMapping(value = "addFileSave")
    @ResponseBody
    private Map<String, String> editFileSave() {
        DocumentBean documentBean = new DocumentBean();
        documentBean.setFileId(request.getParameter("fileId"));
        documentBean.setFileName(request.getParameter("fileName"));
        documentBean.setPath(request.getParameter("path"));
        documentBean.setParentId(request.getParameter("parentId"));
        documentBean.setFileSize(request.getParameter("fileSize"));
        documentBean.setFileType(request.getParameter("fileType"));
        documentBean.setPermission("0");
        documentBean.setCreateBy((String)session.getAttribute(SessionConstant.SESSION_USER_ID));
        documentBean.setUpdateBy((String)session.getAttribute(SessionConstant.SESSION_USER_ID));
        documentBean.setOwnerId((String)session.getAttribute(SessionConstant.SESSION_ORG_ID));
        documentBean.setUid(UUIDUtil.getUUID());
        Map<String, String> resMap = new HashMap<String, String>();
        try {
            Integer res = null;
            if (StringUtil.isEmpty(documentBean.getFileId())) {
                if ("folder".equals(documentBean.getFileType())) {
                    //顶级文件夹路径拼装前缀
                    if ("0".equals(documentBean.getParentId())) {
                        documentBean.setPath(BusinessConstant.FILE_STORE_PREFIX + File.separator + 
                                BusinessConstant.ATTACHMENT_DIR + File.separator + documentBean.getPath());
                    } else {//子级文件夹路径拼装父级路径
                        DocumentBean parent = documentService.getById(documentBean.getParentId());
                        documentBean.setPath(parent.getPath() + File.separator + documentBean.getPath());
                    }
                }
                res = documentService.insert(documentBean);
            } else {
                res = documentService.update(documentBean);
            }
            if (res > 0) {
                resMap.put("result", "SUCCESS");
            } else {
                resMap.put("result", "FAIL");
                resMap.put("message", "成功0条");
            }
            documentService.insertLog(super.MakeLogBean(super.LOG_UPDATE_KEY, "修改文件", documentBean.toString()));
        } catch (BaseException e) {
            e.printStackTrace();
            resMap.put("result", "FAIL");
            resMap.put("message", e.getMessage());
        }
        return resMap;
    }
    
    @RequestMapping(value = "addFolder")
    private String addFolder() {
        return BASE_PATH + "documentAddFolder";
    }

    @RequestMapping(value = "addFolderSave")
    @ResponseBody
    private Map<String, String> addFolderSave() {
        DocumentBean documentBean = new DocumentBean();
        documentBean.setFileName(request.getParameter("fileName"));
        documentBean.setPath(BusinessConstant.FILE_STORE_PREFIX + File.separator + BusinessConstant.ATTACHMENT_DIR + File.separator + request.getParameter("path"));
        documentBean.setParentId(request.getParameter("parentId"));
        documentBean.setFileSize("0");
        documentBean.setFileType("folder");
        documentBean.setCreateBy((String)session.getAttribute(SessionConstant.SESSION_USER_ID));
        documentBean.setOwnerId((String)session.getAttribute(SessionConstant.SESSION_ORG_ID));
        documentBean.setPermission(request.getParameter("permission"));
        documentBean.setUid(UUIDUtil.getUUID());
        Map<String, String> resMap = new HashMap<String, String>();
        try {
            Integer res = documentService.insert(documentBean);
            if (res > 0) {
                resMap.put("result", "SUCCESS");
            } else {
                resMap.put("result", "FAIL");
                resMap.put("message", "插入0条");
            }
            documentService.insertLog(super.MakeLogBean(super.LOG_ADD_KEY, "添加文件夹",documentBean.toString()));
        } catch (BaseException e) {
            e.printStackTrace();
            resMap.put("result", "FAIL");
            resMap.put("message", e.getMessage());
        }
        return resMap;
    }

    @RequestMapping(value = "del")
    private String del(Model model) {
        try {
            String[] ids = request.getParameterValues("ids");
            super.paramMap.put("ids", ids);
            super.paramMap.put("old_param_parentId", super.paramMap.get("param_parentId"));
            super.paramMap.put("old_param_curpage", super.paramMap.get("param_curpage"));
            super.paramMap.remove("param_parentId");
            //初始化页码格式
            super.setPageInfo(20);
            Integer res = documentService.delete(super.paramMap);
            if (res > 0) {
                super.message("删除成功");
                documentService.insertLog(super.MakeLogBean(super.LOG_DELETE_KEY, "删除文件或文件夹", super.paramMap.toString()));
            } else if (res == 0) {
                super.message("删除0条");
            } else {
                super.message("要删除的文件夹中有内容，删除失败");
            }
            dealParamMap();
        } catch (Exception e) {
            super.message("删除失败: " + e.getMessage());
            dealParamMap();
            return getDocumentList(model);
        }
        return getDocumentList(model);
    }
    
    private void dealParamMap() {
        super.paramMap.put("param_parentId", super.paramMap.get("old_param_parentId"));
        super.paramMap.remove("old_param_parentId");
        super.paramMap.remove("parent_ids");
        super.paramMap.put("param_curpage", super.paramMap.get("old_param_curpage"));
        super.paramMap.remove("old_param_curpage");
//        super.paramMap.put("delFailIds", super.paramMap.get("oldIds"));
        super.paramMap.remove(super.paramMap.get("ids"));
    }
}